package com.mzj.saas.mservice.qiyuesuo.service;

import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.bean.Template;
import com.qiyuesuo.sdk.v2.json.JSONUtils;
import com.qiyuesuo.sdk.v2.request.TemplateDetailRequest;
import com.qiyuesuo.sdk.v2.request.TemplateListRequest;
import com.qiyuesuo.sdk.v2.request.TemplatePageRequest;
import com.qiyuesuo.sdk.v2.response.SdkResponse;
import com.qiyuesuo.sdk.v2.response.TemplateListResult;
import com.qiyuesuo.sdk.v2.response.TemplatePageResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 契约锁接口-模板
 * 
 * @author hp
 *
 */
@Service
public class QiYueSuoTemplateService {

	private Logger logger = LoggerFactory.getLogger(QiYueSuoTemplateService.class);

	@Autowired
	private SdkClient sdkClient;

	/**
	 * 获取模板列表 https://open.qiyuesuo.com/document?id=2657160660600767485
	 */
	public List<Template> getTemplateList(String tenantName) {
		TemplateListRequest request = new TemplateListRequest();
		if (StringUtils.isNotBlank(tenantName)) {
			request.setTenantName(tenantName);
		}
		String response = sdkClient.service(request);
		SdkResponse<TemplateListResult> responseObj = JSONUtils.toQysResponse(response, TemplateListResult.class);
		if (responseObj.getCode() == 0) {
			TemplateListResult templateList = responseObj.getResult();
			return templateList.getList();
		} else {
			logger.error("文件模板列表失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
			return null;
		}
	}

	/**
	 * 获取模板详情 https://open.qiyuesuo.com/document?id=2657160735708155950
	 * 
	 * @param templateId
	 * @return
	 */
	public Template getTemplateDetail(Long templateId) {
		if (templateId == null) {
			return null;
		}
		TemplateDetailRequest request = new TemplateDetailRequest(templateId);
		String response = sdkClient.service(request);
		SdkResponse<Template> responseObj = JSONUtils.toQysResponse(response, Template.class);
		if (responseObj.getCode() == 0) {
			return responseObj.getResult();
		} else {
			logger.error("获取模板详情请求失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
			return null;
		}
	}

	/**
	 * 模板预览页面
	 * 
	 * @param templateId
	 * @return 页面链接
	 */
	public String getTemplatePageurl(Long templateId) {
		if (templateId == null) {
			return null;
		}
		TemplatePageRequest request = new TemplatePageRequest(templateId);
		String response = sdkClient.service(request);
		SdkResponse<TemplatePageResult> responseObj = JSONUtils.toQysResponse(response, TemplatePageResult.class);
		if (responseObj.getCode() == 0) {
			return responseObj.getResult().getPageUrl();
		} else {
			logger.error("模板页面查询失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
			return null;
		}
	}
}